package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    private final WmNewsMapper wmNewsMapper;
    //private final GreenTextScan greenTextScan
    private final FileStorageService fileStorageService;
    //private final GreenImageScan greenImageScan
    private final IArticleClient articleClient;
    private final WmChannelMapper wmChannelMapper;
    private final WmUserMapper wmUserMapper;
    private final WmSensitiveMapper wmSensitiveMapper;
    private final Tess4jClient tess4jClient;

    /**
     * 自媒体文章自动审核
     * @param id
     */
    @Override
    @Async  //标明异步调用方法
    public void autoScanNews(Integer id) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        log.info("自动审核文章：{}",wmNews);
        if(wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在！");
        }

        //如果不是待审核状态，直接结束方法
        if(!wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            return;
        }

        //阿里云有问题，直接通过审核
        /*//从内容中抽取文章内容与文章图片
        Map<String, Object> textAndImages = handleTextAndImages(wmNews);

        //自定义敏感词过滤
        boolean isSensitive = handleSensitiveScan((String) textAndImages.get("content"), wmNews);
        if(!isSensitive) {
            return;
        }
        
        //2.审核文章内容（阿里云接口）
        boolean isTextScan = handleTextScan((String) textAndImages.get("content"), wmNews);
        if(!isTextScan) {
            return;
        }

        //3.审核文章图片（阿里云接口）
        boolean isImageScan = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
        if(!isImageScan) {
            return;
        }*/

        //4.审核通过，保存app端相关文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(!responseResult.getCode().equals(200)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存文章失败！");
        }
        //回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        updateWmNews(wmNews, (short) 9, "审核成功");

    }

    /**
     * 审核自定义敏感词
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;

        //从数据库中获取所有敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        //stream流获取所有敏感词
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否有敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "存在敏感词！");
            flag = false;
        }
        return flag;
    }

    /**
     * 保存App端相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        //属性拷贝
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(Long.valueOf(wmNews.getUserId()));
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        if(wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }


    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    /*
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if(images == null || images.size() == 0) {
            return  flag;
        }

        //到MinIO中下载图片
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>();

        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                //图片文字识别
                //byte[]转换为：BufferedImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(in);
                String result = tess4jClient.doOCR(read);
                //过滤文字
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive) {
                    return isSensitive;
                }

                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            //审核失败
            if(map.get("suggestion").equals("block")) {
                updateWmNews(wmNews, (short) 2, "存在违规内容！");
                flag = false;
            }
            //不确定，需人工审核
            if(map.get("suggestion").equals("review")) {
                updateWmNews(wmNews, (short) 3, "存在不确定内容！需转人工！");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
    */


    /**
     * 审核纯文本内容
     * @param content
     * @param wmNews
     * @return
     *
    private boolean handleTextScan(String content, WmNews wmNews) {

        //是否审核成功
        boolean flag = true;

        try {
            //得到阿里云审核结果
            Map map = greenTextScan.greeTextScan(wmNews.getTitle()+ "-" + content);
            if(map != null) {
                //审核失败
                if(map.get("suggestion").equals("block")) {
                    updateWmNews(wmNews, (short) 2, "存在违规内容！");
                    flag = false;
                }
                //不确定，需人工审核
                if(map.get("suggestion").equals("review")) {
                    updateWmNews(wmNews, (short) 3, "存在不确定内容！需转人工！");
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;
    }
    */

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 1.从自媒体文章内容中抽取文章内容与文章图片
     * 2.抽取文章封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();

        //1.从自媒体文章内容中抽取文章内容与文章图片
        if(StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if(map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if(map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }

        //提前文章封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        //构造并返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", images);
        return resultMap;
    }
}
